package com.purengage.ipilih.lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import android.os.Environment;

public class FileHelper {

	String directory;

	public FileHelper(String d) {
		directory = d;
	}
	
	public boolean isFile(String fname){
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() +"/"+ directory);
		
		File f = new File(dir, fname);
		if (!f.exists()) 
			return false;
		else return true;
		
	}
	


	public boolean delete(String fname) throws IOException{
		
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() +"/"+ directory);
		
		File f = new File(dir, fname);
		
		if (f.exists()) {			
			f.delete();
			return true;
		}
		
		return false;
	}
	
	public boolean write(String fname, String content) {

		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() +"/"+ directory);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		File f = new File(dir, fname);
		if (!f.exists()) {

			try {
				f.createNewFile();
				FileWriter out = new FileWriter(f);
				out.write(content);
				out.close();
				
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return false;
	}
	
	public String read(String fname){
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() +"/"+ directory);				
		File f = new File(dir, fname);
		
		String aBuffer = null;
		
		try {			
           
            final FileInputStream fIn = new FileInputStream(f);
            final BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
            String aDataRow;
            aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                if (!aDataRow.equals("")) {
                    aBuffer += aDataRow;
                }
            }
            myReader.close();

        } catch (final FileNotFoundException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        }
		
		return aBuffer;
	}
}
